import { mapState } from 'vuex';
import { getProductAll, refundOrder } from '@/api/index.js'
import { queryOrdersByPrarmSt, queryAllOrders } from '@/api/new.js'
import { updateOrder } from '@/api/new1.js'

export default {
  data() {
    return {
      navIndex: 1,
      queryAllOrder:[],
      updateOrder:[],
      afterSalesbox:1,
      dataobj:{
        item:{},
        statu:'',
      },
      gecodes:[],
      latitude: 31.322542,
      longitude: 121.265584,
      scale: 15,
      markers: [],
      isMap: false,
      isTab: true,
      btnLeft: 300,
      btnTop: 300,
      startX: 0,
      startY: 0,
      isMoving: false,
      windowWidth: 0,
      windowHeight: 0,
	   showUploadBtn: true // 新增：控制上传按钮显示
    }
  },
  computed: {
    ...mapState({
      loginStatus: state => state.user.loginStatus,
      userInfo: state => state.user.userInfo
    })
  },
  mounted() {
    this.checkIndex(1,1)
    this.initButtonPosition()
    uni.getSystemInfo({
      success: (res) => {
        this.windowWidth = res.windowWidth
        this.windowHeight = res.windowHeight
        this.btnLeft = res.windowWidth - 100
        this.btnTop = res.windowHeight - 200
      }
    })
  },
  methods: {
    checkIndex(index, status) {
      console.log(index)
      if(this.loginStatus==true){
        this.navIndex = index
        
        // 新增：根据tab控制上传按钮显示
        this.showUploadBtn = index !== 2
        
        if(index === 2){ 
          this.isTab = false
          this.isMap = true
          this.queryAllOrder = []
          
          var data = {
            storeId: this.userInfo.storeId,
            statusArr: [1,2]
          }
          queryOrdersByPrarmSt(data).then(res => {
            this.initMapData(res.data.data)
          })
        } else {
          this.isTab = true
          this.isMap = false
          
          var data = {
            storeId: this.userInfo.storeId,
            status: status
          }
          queryOrdersByPrarmSt(data).then(res => {
            this.queryAllOrder = res.data.data
          })
        }
      }else{
        uni.navigateTo({
          url: '/pages/login/index'
        })
      }
    },
    delivery2(){
      this.afterSalesbox = 1
      if(this.dataobj.statu == 7){
        var data = {
          orderId: this.dataobj.item.orderId
        }
        refundOrder(data).then(res => {
          uni.showToast({
            title: '操作成功,已同意退款申请',
            icon:"none"
          })
        })
      }else if(this.dataobj.statu == 8){
        this.dataobj.item = item
        this.dataobj.statu = statu
        let data = this.dataobj.item
        data.status = this.dataobj.statu
        updateOrder(data).then(res => {
          uni.showToast({
            title: '操作成功',
            icon:'none'
          })
        })
      }
      this.checkIndex(this.navIndex,this.dataobj.statu)
    },
    delivery(item,statu,val,now){
      if(statu == 7){
        this.dataobj.item = item
        this.dataobj.statu = statu
        this.afterSalesbox = val
      }else if(statu == 8){
        this.dataobj.item = item
        this.dataobj.statu = statu
        this.afterSalesbox = val
      }else{
        var data = item
        data.status = statu
        updateOrder(data).then(res => {
          this.checkIndex(this.navIndex,now)
          uni.showToast({
            title: '操作成功',
            icon:'none'
          })
          this.refreshMapData()
        })
      }
    },	
    refreshMapData() {
      var data = {
        storeId: this.userInfo.storeId,
        statusArr: [1, 2]
      }
      queryOrdersByPrarmSt(data).then(res => {
        this.initMapData(res.data.data)
      })
    },
    navigateToMapMer(item) {
      const address = item.receiverAddress
      if (address) {
        uni.request({
          url: "https://apis.map.qq.com/ws/geocoder/v1?address="+address+"&key=MWBBZ-NU3L4-UUZUX-KC2TQ-RC4N6-KNBZN",
          success: function (res) {
            console.log('请求地图api出参:'+JSON.stringify(res))
            if (res.data.status === 347) {
              uni.showToast({
                icon: "error",
                title: "地址查询无结果",
              })
            }
            const location = res.data.result.location
            const latitude = location.lat
            const longitude = location.lng
            uni.openLocation({
              name: address,
              address: address,
              latitude: latitude,
              longitude: longitude,
              success: () => {
                console.log("打开地图成功")
                this.refreshMapData()
              },
              fail: (err) => {
                console.error("打开地图失败", err)
              },
            })
          },
          fail: function (err) {
            console.error("获取地址经纬度失败", err)
          },
        })
      }
    },
    navigateToMapMer2(item) {
      const address = item.receiverAddress
      if (address) {
        uni.request({
          url: "https://restapi.amap.com/v3/geocode/geo",
          data: {
            address: address,
            key: "47fa3bcc499016104283079c04177447",
          },
          success: function (res1) {
            this.gecodes = res1.data.geocodes
            if (this.gecodes.length<1) {
              uni.showToast({
                icon: "error",
                title: "地址查询无结果",
              })
            }
            const formatted_address =this.gecodes[0].formatted_address
            console.log('formatted_address->'+formatted_address)
            const location =this.gecodes[0].location
            const llres = location.split(',')
            const latitude = parseFloat(llres[0])
            const longitude = parseFloat(llres[1])
            console.log(location, "纬度：" + latitude + "，经度：" + longitude)
            uni.openLocation({
              name: address,
              address: address,
              latitude: latitude,
              longitude: longitude,
              success: () => {
                console.log("打开地图成功")
              },
              fail: (err) => {
                console.error("打开地图失败", err)
              },
            })
          },
          fail: function (err) {
            console.error("获取地址经纬度失败", err)
          },
        })
      }
    },
    tocall(data){
      this.afterSalesbox = 1
      uni.makePhoneCall({
        phoneNumber:data,
        success:function(e){
          console.log(e)
        },
        fail:function(e){
          console.log(e)
        }
      })
    },
    handleToSearch() {
      uni.navigateTo({
        url: '/pages/search/search'
      })
    },	
    initMapData(orderData) {
      uni.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        success: (res) => {
          console.log('用户当前位置:', res.longitude, res.latitude)
          this.longitude = res.longitude
          this.latitude = res.latitude
          
          const markers = orderData.map((order) => {
            const distance = this.calcDistance(
              res.latitude, 
              res.longitude,
              order.receiverLatitude,
              order.receiverLongitude
            )
            let address = ''
            // 新增：根据 orderType 判断显示内容
            let titleContent = ''
            if (order.orderType && order.orderType.startsWith('m-')) {
              // 如果 orderType 以 'm-' 开头，使用 remark
              titleContent = order.remark || '无备注信息'
            } else {
              // 否则拼接所有商品信息
              const productsInfo = order.orderProducts.map(product => {
                return `${product.productName}*${product.count}`
              }).join(' & ') // 使用 & 符号拼接
              titleContent = productsInfo
			  address = order.receiverAddress || ''
			  address = address.replace(/^.*?(省|自治区|直辖市)/, '')
			                  .replace(/^.*?(市|自治州|地区|盟)/, '')
			                  .replace(/^.*?(区|县|旗|市)/, '')
			                  .trim()
            }
            
            
            console.log('address-->'+address)
            return {
              id: order.orderId,
              latitude: order.receiverLatitude,
              longitude: order.receiverLongitude,
              title: `${titleContent} (${distance}km)`, // 使用处理后的内容
              iconPath: this.getMarkerIconByStatus(order.status),
              width: 30,
              height: 30,
              callout: {
                content: `商品: ${titleContent}\n地址: ${address}\n距离: ${distance}km`,
                color: '#333',
                fontSize: 14,
                borderRadius: 5,
                bgColor: '#fff',
                padding: 10,
                display: 'ALWAYS'
              },
              customData: order
            }
          })
          
          markers.push({
            id: 1001,
            latitude: res.latitude,
            longitude: res.longitude,
            title: '我的位置',
            iconPath: '/static/image/mylocation.png',
            width: 30,
            height: 30,
            callout: {
              content: '我的当前位置',
              color: '#333',
              fontSize: 14,
              borderRadius: 5,
              bgColor: '#fff',
              padding: 10,
              display: 'ALWAYS'
            }
          })
          
          this.markers = markers
          
          this.$nextTick(() => {
            const mapContext = uni.createMapContext('orderMap', this)
            mapContext.includePoints({
              points: markers,
              padding: [50, 50, 50, 50]
            })
          })
        },
        fail: (err) => {
          console.log('获取位置失败:', err)
          uni.showToast({
            title: '获取位置失败',
            icon: 'none'
          })
        }
      })
    },
    getMarkerIconByStatus(status) {
      const icons = {
        1: '/static/image/pending.png',
        2: '/static/image/deliverInProgress.png'
      }
      return icons[status] || '/static/image/marker-default.png'
    },
    calcDistance(lat1, lon1, lat2, lon2) {
      const R = 6371
      const dLat = (lat2 - lat1) * Math.PI / 180
      const dLon = (lon2 - lon1) * Math.PI / 180
      const a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
        Math.sin(dLon/2) * Math.sin(dLon/2)
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
      const distance = R * c
      return distance.toFixed(2)
    },
    onMarkerTap(e) {
      const markerId = e.markerId
      const marker = this.markers.find(m => m.id === markerId)
      
      if (markerId === 1001) return
      
      if (marker.customData && marker.customData.status === 1) {
        uni.showActionSheet({
          itemList: ['导航到目的地', '立即配送'],
          success: (res) => {
            if (res.tapIndex === 0) {
              this.navigateToMapMer(marker.customData)
            } else if (res.tapIndex === 1) {
              this.delivery(marker.customData, 2, 0, 1)
            }
          }
        })
      } else {
        uni.showToast({
          title: `点击了订单 ${markerId}`,
          icon: 'none'
        })
      }
    },
    handleUploadOrder() {
      // 替换原来的 toast 提示
      uni.navigateTo({
        url: '/pages/upOrder/upOrder'
      });
    },
    initButtonPosition() {
      this.btnLeft = this.windowWidth - 100
      this.btnTop = this.windowHeight - 200
    },
    touchStart(e) {
      this.startX = e.touches[0].clientX
      this.startY = e.touches[0].clientY
      this.isMoving = false
    },
    touchMove(e) {
      const moveX = e.touches[0].clientX
      const moveY = e.touches[0].clientY
      
      const diffX = moveX - this.startX
      const diffY = moveY - this.startY
      
      if (Math.abs(diffX) > 10 || Math.abs(diffY) > 10) {
        this.isMoving = true
      }
      
      let newLeft = this.btnLeft + diffX
      let newTop = this.btnTop + diffY
      
      newLeft = Math.max(0, Math.min(newLeft, this.windowWidth - 100))
      newTop = Math.max(0, Math.min(newTop, this.windowHeight - 60))
      
      this.btnLeft = newLeft
      this.btnTop = newTop
      
      this.startX = moveX
      this.startY = moveY
    },
    touchEnd() {
      if (!this.isMoving) {
        this.handleUploadOrder()
      }
      this.isMoving = false
    },
    handleUploadClick() {
      if (!this.isMoving) {
        this.handleUploadOrder()
      }
    }
  }
}